package com.exject.android.socialphonebook.util;

import java.util.ArrayList;
import java.util.List;

import android.R;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.provider.CallLog;
import android.provider.Contacts;
import android.provider.Contacts.ContactMethodsColumns;
import android.provider.Contacts.OrganizationColumns;
import android.provider.Contacts.People;
import android.provider.Contacts.PeopleColumns;
import android.provider.Contacts.PhonesColumns;
import android.text.format.DateUtils;
import android.util.Log;

import com.exject.android.socialphonebook.data.Address;
import com.exject.android.socialphonebook.data.ChatAddress;
import com.exject.android.socialphonebook.data.Contact;
import com.exject.android.socialphonebook.data.ContactList;
import com.exject.android.socialphonebook.data.EMailAddress;
import com.exject.android.socialphonebook.data.Note;
import com.exject.android.socialphonebook.data.Organization;
import com.exject.android.socialphonebook.data.PhoneNumber;
import com.exject.android.socialphonebook.data.Type;

public class RetrieveContactHelper {
    private final static String PEOPLE_ID = "_id";
    private Cursor cursor;
    private ContentResolver contentResolver;
    
    public RetrieveContactHelper(ContentResolver contentResolver) {
        this.contentResolver = contentResolver;
    }
    
    private List<Address> getContactAddresses(final long id) {
        final ArrayList<Address> addrList = new ArrayList<Address>();
        
        final String where = Contacts.ContactMethods.PERSON_ID + " = ? AND "
                + ContactMethodsColumns.KIND + " = ?";
        final String[] whereParameters = new String[] { "" + id,
                "" + Contacts.KIND_POSTAL };
        
        final Cursor addrCur = this.contentResolver.query(
                Contacts.ContactMethods.CONTENT_URI, null, where,
                whereParameters, null);
        while (addrCur.moveToNext()) {
            final String addr = addrCur.getString(addrCur
                    .getColumnIndex(Contacts.ContactMethodsColumns.DATA));
            final String type = addrCur.getString(addrCur
                    .getColumnIndex(Contacts.ContactMethodsColumns.TYPE));
            final Address a = new Address(new Type(type), addr);
            addrList.add(a);
        }
        addrCur.close();
        return (addrList);
    }
    
        
    private List<Organization> getContactOrganization(final long id) {
        final List<Organization> orgs = new ArrayList<Organization>();
        final String where = Contacts.ContactMethods.PERSON_ID + " = ?";
        final String[] whereParameters = new String[] { "" + id };
        
        final Cursor orgCur = this.contentResolver.query(
                Contacts.Organizations.CONTENT_URI, null, where,
                whereParameters, null);
        for (int i = 0; i < orgCur.getCount(); i++) {
            orgCur.moveToNext();
            Organization org = new Organization();
            final String orgName = orgCur.getString(orgCur
                    .getColumnIndex(OrganizationColumns.COMPANY));
            final String position = orgCur.getString(orgCur
                    .getColumnIndex(OrganizationColumns.TITLE));
            if (orgName.length() > 0) {
                org.setCompanyName(orgName);
                org.setPosition(position);
            }
            orgs.add(org);
        }
        orgCur.close();
        return (orgs);
    }
    
    private List<EMailAddress> getEmailAddresses(final long id) {
        final ArrayList<EMailAddress> emails = new ArrayList<EMailAddress>();
        
        final String where = Contacts.ContactMethods.PERSON_ID + " = ? AND "
                + ContactMethodsColumns.KIND + " = ?";
        final String[] whereParameters = new String[] { "" + id,
                "" + Contacts.KIND_EMAIL };
        
        final Cursor emailCur = this.contentResolver.query(
                Contacts.ContactMethods.CONTENT_URI, null, where,
                whereParameters, null);
        
        while (emailCur.moveToNext()) {
            // This would allow you get several email addresses
            final EMailAddress e = new EMailAddress(
                    new Type(emailCur.getString(emailCur
                            .getColumnIndex(ContactMethodsColumns.TYPE))),
                    emailCur
                            .getString(emailCur
                                    .getColumnIndex(Contacts.ContactMethodsColumns.DATA)));
            emails.add(e);
        }
        emailCur.close();
        return (emails);
    }
    
    private List<ChatAddress> getIM(final long id) {
        final ArrayList<ChatAddress> imList = new ArrayList<ChatAddress>();
        final String where = Contacts.ContactMethods.PERSON_ID + " = ? AND "
                + ContactMethodsColumns.KIND + " = ?";
        final String[] whereParameters = new String[] { "" + id,
                Contacts.ContactMethods.CONTENT_IM_ITEM_TYPE };
        
        final Cursor imCur = this.contentResolver.query(
                Contacts.ContactMethods.CONTENT_URI, null, where,
                whereParameters, null);
        if (imCur.moveToFirst()) {
            final String imName = imCur.getString(imCur
                    .getColumnIndex(Contacts.ContactMethodsColumns.DATA));
            final String protocol = imCur.getString(imCur
                    .getColumnIndex(Contacts.ContactMethodsColumns.TYPE));
            if (imName.length() > 0) {
                final ChatAddress im = new ChatAddress(protocol, imName);
                imList.add(im);
            }
        }
        imCur.close();
        return (imList);
    }
    
    private List<PhoneNumber> getPhoneNumbers(final long id) {
        final ArrayList<PhoneNumber> phones = new ArrayList<PhoneNumber>();
        
        final Cursor pCur = this.contentResolver.query(
                Contacts.Phones.CONTENT_URI, null, Contacts.Phones.PERSON_ID
                        + " = ?", new String[] { "" + id }, null);
        while (pCur.moveToNext()) {
            phones.add(new PhoneNumber(new Type(pCur.getString(pCur
                    .getColumnIndex(PhonesColumns.TYPE))), pCur.getString(pCur
                    .getColumnIndex(PhonesColumns.NUMBER))));
            
        }
        pCur.close();
        return (phones);
    }
    
    public ContactList getContactList() {
        final ContactList contacts = new ContactList();
        
        this.cursor = this.contentResolver.query(People.CONTENT_URI, null,
                null, null, null);
        if (this.cursor.getCount() > 0) {
            while (this.cursor.moveToNext()) {
                final Contact contact = new Contact();
                long id = this.cursor.getLong(this.cursor
                        .getColumnIndex(PEOPLE_ID));
                contact.setId(id);
                contact.setName(this.cursor.getString(this.cursor
                        .getColumnIndex(PeopleColumns.DISPLAY_NAME)));
                if (Integer.parseInt(this.cursor.getString(this.cursor
                        .getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
                    contact.setPhoneNumbers(this.getPhoneNumbers(id));
                }
                contact.setEMailAddresses(this.getEmailAddresses(id));
                final List<Note> notes = new ArrayList<Note>();
                notes.add(new Note(this.cursor.getString(this.cursor
                        .getColumnIndex(PeopleColumns.NOTES))));
                contact.setNotes(notes);
                contact.setAddresses(this.getContactAddresses(id));
                contact.setChatAddresses(this.getIM(id));
                contact.setOrganizations(this.getContactOrganization(id));
                contacts.addContact(contact);
            }
        }
        return (contacts);
    }
    
    public Contact getContactByName(final String name) {
        Contact contact = null;
        
        this.cursor = this.contentResolver.query(People.CONTENT_URI, null,
                People.NAME + " LIKE ?", new String[] { name }, null);
        if (this.cursor.getCount() > 0) {
            while (this.cursor.moveToNext()) {
                contact = new Contact();
                long id = this.cursor.getLong(this.cursor
                        .getColumnIndex(People._ID));
                contact.setId(id);
                contact.setName(this.cursor.getString(this.cursor
                        .getColumnIndex(PeopleColumns.DISPLAY_NAME)));
                if (Integer.parseInt(this.cursor.getString(this.cursor
                        .getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
                    contact.setPhoneNumbers(this.getPhoneNumbers(id));
                }
                contact.setEMailAddresses(this.getEmailAddresses(id));
                final List<Note> notes = new ArrayList<Note>();
                notes.add(new Note(this.cursor.getString(this.cursor
                        .getColumnIndex(PeopleColumns.NOTES))));
                contact.setNotes(notes);
                contact.setAddresses(this.getContactAddresses(id));
                contact.setChatAddresses(this.getIM(id));
                contact.setOrganizations(this.getContactOrganization(id));
            }
        }
        
        return (contact);
    }
    
    public Contact getContactById(final long id) {
        Contact contact = null;
        
        this.cursor = this.contentResolver.query(ContentUris.withAppendedId(
                People.CONTENT_URI, id), null, null, null, null);
        Log.i("AtracuraPhonebook RetrieveContactHelper.getContactById", ""
                + this.cursor.getCount());
        if (this.cursor.getCount() > 0) {
            while (this.cursor.moveToNext()) {
                contact = new Contact();
                contact.setId(id);
                contact.setName(this.cursor.getString(this.cursor
                        .getColumnIndex(PeopleColumns.DISPLAY_NAME)));
                if (Integer.parseInt(this.cursor.getString(this.cursor
                        .getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
                    contact.setPhoneNumbers(this.getPhoneNumbers(id));
                }
                contact.setEMailAddresses(this.getEmailAddresses(id));
                final List<Note> notes = new ArrayList<Note>();
                notes.add(new Note(this.cursor.getString(this.cursor
                        .getColumnIndex(PeopleColumns.NOTES))));
                contact.setNotes(notes);
                contact.setAddresses(this.getContactAddresses(id));
                contact.setChatAddresses(this.getIM(id));
                contact.setOrganizations(this.getContactOrganization(id));
            }
        }
        return (contact);
    }
}
